// 渲染系统模块

class Renderer {
    constructor(canvas) {
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');
        this.animationId = null;
        this.lastTime = 0;
        this.fps = 60;
        this.frameTime = 1000 / this.fps;
        
        // 设置画布属性
        this.setupCanvas();
    }

    // 设置画布
    setupCanvas() {
        // 设置高DPI支持
        const dpr = window.devicePixelRatio || 1;
        
        // 获取容器尺寸
        const container = this.canvas.parentElement;
        const containerRect = container.getBoundingClientRect();
        
        // 计算合适的画布尺寸，保持3:4的宽高比
        let canvasWidth = Math.min(containerRect.width - 20, 400);
        let canvasHeight = canvasWidth * 1.5; // 3:4比例
        
        // 在移动设备上调整尺寸
        if (window.innerWidth <= 480) {
            canvasWidth = Math.min(containerRect.width - 10, 320);
            canvasHeight = canvasWidth * 1.5;
        }
        
        // 设置画布实际尺寸
        this.canvas.width = canvasWidth * dpr;
        this.canvas.height = canvasHeight * dpr;
        
        // 设置画布显示尺寸
        this.canvas.style.width = canvasWidth + 'px';
        this.canvas.style.height = canvasHeight + 'px';
        
        // 更新游戏配置
        GAME_CONFIG.updateContainer(canvasWidth, canvasHeight);
        
        this.ctx.scale(dpr, dpr);
        
        // 设置渲染质量
        this.ctx.imageSmoothingEnabled = true;
        this.ctx.imageSmoothingQuality = 'high';
    }

    // 开始渲染循环
    startRenderLoop(physicsEngine, gameState) {
        this.physicsEngine = physicsEngine;
        this.gameState = gameState;
        
        const renderFrame = (currentTime) => {
            const deltaTime = currentTime - this.lastTime;
            
            if (deltaTime >= this.frameTime) {
                this.render();
                this.lastTime = currentTime;
            }
            
            this.animationId = requestAnimationFrame(renderFrame);
        };
        
        this.animationId = requestAnimationFrame(renderFrame);
    }

    // 停止渲染循环
    stopRenderLoop() {
        if (this.animationId) {
            cancelAnimationFrame(this.animationId);
            this.animationId = null;
        }
    }

    // 主渲染函数
    render() {
        // 清空画布
        this.clearCanvas();
        
        // 绘制背景
        this.drawBackground();
        
        // 绘制容器
        this.drawContainer();
        
        // 绘制游戏结束线
        this.drawGameOverLine();
        
        // 绘制球体
        this.drawBalls();
        
        // 绘制粒子效果
        this.drawParticles();
        
        // 绘制投放预览
        this.drawDropPreview();
        
        // 绘制UI元素
        this.drawUI();
    }

    // 清空画布
    clearCanvas() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }

    // 绘制背景
    drawBackground() {
        const gradient = this.ctx.createLinearGradient(0, 0, 0, this.canvas.height);
        gradient.addColorStop(0, '#e6f3ff');
        gradient.addColorStop(1, '#cce7ff');
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }

    // 绘制容器
    drawContainer() {
        const container = this.physicsEngine.getContainer();
        const { width, height, x, y } = container;
        
        // 绘制容器边框
        this.ctx.strokeStyle = '#4a5568';
        this.ctx.lineWidth = 3;
        this.ctx.setLineDash([]);
        
        // 底部
        this.ctx.beginPath();
        this.ctx.moveTo(x - width/2, y);
        this.ctx.lineTo(x + width/2, y);
        this.ctx.stroke();
        
        // 左侧
        this.ctx.beginPath();
        this.ctx.moveTo(x - width/2, y);
        this.ctx.lineTo(x - width/2, y - height);
        this.ctx.stroke();
        
        // 右侧
        this.ctx.beginPath();
        this.ctx.moveTo(x + width/2, y);
        this.ctx.lineTo(x + width/2, y - height);
        this.ctx.stroke();
    }

    // 绘制游戏结束线
    drawGameOverLine() {
        const container = this.physicsEngine.getContainer();
        const gameOverY = GAME_CONFIG.gameplay.gameOverLine;
        
        this.ctx.strokeStyle = '#ff4757';
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        
        this.ctx.beginPath();
        this.ctx.moveTo(container.x - container.width/2, gameOverY);
        this.ctx.lineTo(container.x + container.width/2, gameOverY);
        this.ctx.stroke();
        
        // 重置线条样式
        this.ctx.setLineDash([]);
    }

    // 绘制球体
    drawBalls() {
        const balls = this.physicsEngine.getBalls();
        
        balls.forEach(ball => {
            this.drawBall(ball);
        });
    }

    // 绘制单个球体
    drawBall(ball) {
        const { x, y } = ball.body.position;
        const radius = ball.radius;
        const color = ball.color;
        
        this.ctx.save();
        
        // 绘制球体阴影
        this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
        this.ctx.shadowBlur = 5;
        this.ctx.shadowOffsetX = 2;
        this.ctx.shadowOffsetY = 2;
        
        // 绘制球体主体
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        
        // 创建渐变效果
        const gradient = this.ctx.createRadialGradient(
            x - radius/3, y - radius/3, 0,
            x, y, radius
        );
        
        if (ball.level === 9) {
            // 9级球特殊效果
            gradient.addColorStop(0, '#ffed4e');
            gradient.addColorStop(0.7, '#ffd700');
            gradient.addColorStop(1, '#ffb300');
            
            // 添加光环效果
            this.ctx.shadowColor = '#ffd700';
            this.ctx.shadowBlur = 15;
        } else {
            gradient.addColorStop(0, this.lightenColor(color, 0.3));
            gradient.addColorStop(0.7, color);
            gradient.addColorStop(1, this.darkenColor(color, 0.2));
        }
        
        this.ctx.fillStyle = gradient;
        this.ctx.fill();
        
        // 绘制球体边框
        this.ctx.shadowColor = 'transparent';
        this.ctx.strokeStyle = this.darkenColor(color, 0.3);
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
        
        // 绘制等级数字
        this.drawBallLevel(x, y, ball.level, radius);
        
        // 绘制高光
        this.drawBallHighlight(x, y, radius);
        
        this.ctx.restore();
    }

    // 绘制球体等级数字
    drawBallLevel(x, y, level, radius) {
        this.ctx.fillStyle = '#ffffff';
        this.ctx.strokeStyle = '#333333';
        this.ctx.lineWidth = 1;
        this.ctx.font = `bold ${Math.max(12, radius * 0.8)}px Arial`;
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        
        // 绘制文字描边
        this.ctx.strokeText(level.toString(), x, y);
        // 绘制文字填充
        this.ctx.fillText(level.toString(), x, y);
    }

    // 绘制球体高光
    drawBallHighlight(x, y, radius) {
        const highlightGradient = this.ctx.createRadialGradient(
            x - radius/3, y - radius/3, 0,
            x - radius/3, y - radius/3, radius/2
        );
        
        highlightGradient.addColorStop(0, 'rgba(255, 255, 255, 0.6)');
        highlightGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
        
        this.ctx.fillStyle = highlightGradient;
        this.ctx.beginPath();
        this.ctx.arc(x - radius/3, y - radius/3, radius/2, 0, Math.PI * 2);
        this.ctx.fill();
    }

    // 绘制增强粒子效果
    drawParticles() {
        const particles = this.physicsEngine.getParticles();
        
        particles.forEach(particle => {
            this.ctx.save();
            
            switch (particle.type) {
                case 'explosion':
                    this.drawExplosionParticle(particle);
                    break;
                case 'stardust':
                    this.drawStardustParticle(particle);
                    break;
                case 'magic':
                    this.drawMagicParticle(particle);
                    break;
                case 'shockwave':
                    this.drawShockwaveParticle(particle);
                    break;
                default:
                    // 兼容旧版粒子
                    this.ctx.globalAlpha = particle.life;
                    this.ctx.fillStyle = particle.color;
                    this.ctx.beginPath();
                    this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
                    this.ctx.fill();
                    break;
            }
            
            this.ctx.restore();
        });
    }
    
    // 绘制爆炸粒子（带色差效果）
    drawExplosionParticle(particle) {
        const alpha = particle.life;
        const glowIntensity = particle.glowIntensity || 0.5;
        const chromaticOffset = particle.chromaticOffset || 1;
        
        // 发光效果
        this.ctx.shadowColor = particle.color;
        this.ctx.shadowBlur = particle.size * glowIntensity * 3;
        
        // 色差效果 - 绘制RGB分离
        const offsetX = chromaticOffset * (1 - alpha);
        const offsetY = chromaticOffset * (1 - alpha) * 0.5;
        
        // 红色通道
        this.ctx.globalAlpha = alpha * 0.7;
        this.ctx.fillStyle = this.getRedChannel(particle.color);
        this.ctx.beginPath();
        this.ctx.arc(particle.x - offsetX, particle.y - offsetY, particle.size, 0, Math.PI * 2);
        this.ctx.fill();
        
        // 绿色通道
        this.ctx.fillStyle = this.getGreenChannel(particle.color);
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        this.ctx.fill();
        
        // 蓝色通道
        this.ctx.fillStyle = this.getBlueChannel(particle.color);
        this.ctx.beginPath();
        this.ctx.arc(particle.x + offsetX, particle.y + offsetY, particle.size, 0, Math.PI * 2);
        this.ctx.fill();
        
        // 主体粒子
        this.ctx.globalAlpha = alpha;
        this.ctx.fillStyle = particle.color;
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        this.ctx.fill();
    }
    
    // 绘制星尘粒子（闪烁效果）
    drawStardustParticle(particle) {
        const alpha = particle.life;
        let sparkleAlpha = alpha;
        
        if (particle.sparkle) {
            sparkleAlpha = alpha * (0.5 + 0.5 * Math.sin(particle.sparklePhase));
        }
        
        // 发光效果
        this.ctx.shadowColor = '#ffffff';
        this.ctx.shadowBlur = particle.size * 4;
        
        // 星形闪烁
        this.ctx.globalAlpha = sparkleAlpha;
        this.ctx.fillStyle = particle.color;
        
        // 绘制十字星形
        const starSize = particle.size * 2;
        this.ctx.fillRect(particle.x - starSize/2, particle.y - 0.5, starSize, 1);
        this.ctx.fillRect(particle.x - 0.5, particle.y - starSize/2, 1, starSize);
        
        // 绘制中心点
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        this.ctx.fill();
    }
    
    // 绘制魔法粒子（轨迹效果）
    drawMagicParticle(particle) {
        const alpha = particle.life;
        
        // 绘制轨迹
        if (particle.trail && particle.trail.length > 1) {
            this.ctx.strokeStyle = particle.color;
            this.ctx.lineWidth = particle.size;
            this.ctx.lineCap = 'round';
            
            for (let i = 0; i < particle.trail.length - 1; i++) {
                const trailAlpha = (particle.trail[i].life || 0) * 0.3;
                this.ctx.globalAlpha = trailAlpha;
                
                this.ctx.beginPath();
                this.ctx.moveTo(particle.trail[i].x, particle.trail[i].y);
                this.ctx.lineTo(particle.trail[i + 1].x, particle.trail[i + 1].y);
                this.ctx.stroke();
            }
        }
        
        // 发光效果
        this.ctx.shadowColor = particle.color;
        this.ctx.shadowBlur = particle.size * 3;
        
        // 主体粒子
        this.ctx.globalAlpha = alpha;
        this.ctx.fillStyle = particle.color;
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        this.ctx.fill();
    }
    
    // 绘制冲击波粒子
    drawShockwaveParticle(particle) {
        const alpha = (particle.alpha || 0.3) * particle.life;
        
        this.ctx.globalAlpha = alpha;
        this.ctx.strokeStyle = particle.color;
        this.ctx.lineWidth = 2;
        
        // 绘制扩散圆环
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        this.ctx.stroke();
        
        // 内部发光
        if (particle.size > 5) {
            this.ctx.globalAlpha = alpha * 0.3;
            this.ctx.fillStyle = particle.color;
            this.ctx.beginPath();
            this.ctx.arc(particle.x, particle.y, particle.size - 2, 0, Math.PI * 2);
            this.ctx.fill();
        }
    }
    
    // 色彩通道分离工具函数
    getRedChannel(color) {
        const rgb = this.hexToRgb(color);
        return `rgba(${rgb.r}, 0, 0, 1)`;
    }
    
    getGreenChannel(color) {
        const rgb = this.hexToRgb(color);
        return `rgba(0, ${rgb.g}, 0, 1)`;
    }
    
    getBlueChannel(color) {
        const rgb = this.hexToRgb(color);
        return `rgba(0, 0, ${rgb.b}, 1)`;
    }
    
    hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : { r: 255, g: 255, b: 255 };
    }

    // 绘制投放预览
    drawDropPreview() {
        if (!this.gameState || this.gameState.isGameOver) return;
        
        const mouseX = this.gameState.mouseX;
        const nextLevel = this.physicsEngine.nextBallLevel;
        
        if (mouseX !== undefined && nextLevel) {
            const dropZone = GAME_CONFIG.gameplay.dropZone;
            const clampedX = Utils.clamp(mouseX, dropZone.x, dropZone.x + dropZone.width);
            const previewY = dropZone.y;
            
            // 绘制投放线
            this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
            this.ctx.lineWidth = 2;
            this.ctx.setLineDash([5, 5]);
            
            this.ctx.beginPath();
            this.ctx.moveTo(clampedX, 0);
            this.ctx.lineTo(clampedX, previewY);
            this.ctx.stroke();
            
            this.ctx.setLineDash([]);
            
            // 绘制预览球体
            const previewRadius = Utils.getBallSize(nextLevel);
            const previewColor = Utils.getBallColor(nextLevel);
            
            this.ctx.save();
            this.ctx.globalAlpha = 0.7;
            
            const gradient = this.ctx.createRadialGradient(
                clampedX - previewRadius/3, previewY - previewRadius/3, 0,
                clampedX, previewY, previewRadius
            );
            
            gradient.addColorStop(0, this.lightenColor(previewColor, 0.3));
            gradient.addColorStop(0.7, previewColor);
            gradient.addColorStop(1, this.darkenColor(previewColor, 0.2));
            
            this.ctx.fillStyle = gradient;
            this.ctx.beginPath();
            this.ctx.arc(clampedX, previewY, previewRadius, 0, Math.PI * 2);
            this.ctx.fill();
            
            // 绘制等级数字
            this.drawBallLevel(clampedX, previewY, nextLevel, previewRadius);
            
            this.ctx.restore();
        }
    }

    // 绘制UI元素
    drawUI() {
        // 可以在这里绘制额外的UI元素，如分数、连击等
        // 目前主要UI通过HTML/CSS实现
    }

    // 颜色工具函数
    lightenColor(color, amount) {
        const num = parseInt(color.replace('#', ''), 16);
        const amt = Math.round(2.55 * amount * 100);
        const R = (num >> 16) + amt;
        const G = (num >> 8 & 0x00FF) + amt;
        const B = (num & 0x0000FF) + amt;
        
        return '#' + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
            (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
            (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1);
    }

    darkenColor(color, amount) {
        const num = parseInt(color.replace('#', ''), 16);
        const amt = Math.round(2.55 * amount * 100);
        const R = (num >> 16) - amt;
        const G = (num >> 8 & 0x00FF) - amt;
        const B = (num & 0x0000FF) - amt;
        
        return '#' + (0x1000000 + (R > 255 ? 255 : R < 0 ? 0 : R) * 0x10000 +
            (G > 255 ? 255 : G < 0 ? 0 : G) * 0x100 +
            (B > 255 ? 255 : B < 0 ? 0 : B)).toString(16).slice(1);
    }

    // 设置鼠标位置（用于预览）
    setMousePosition(x, y) {
        if (this.gameState) {
            this.gameState.mouseX = x;
            this.gameState.mouseY = y;
        }
    }

    // 清除鼠标位置
    clearMousePosition() {
        if (this.gameState) {
            this.gameState.mouseX = undefined;
            this.gameState.mouseY = undefined;
        }
    }

    // 截图功能
    takeScreenshot() {
        return this.canvas.toDataURL('image/png');
    }

    // 调整画布大小
    resize() {
        this.setupCanvas();
    }

    // 设置FPS
    setFPS(fps) {
        this.fps = fps;
        this.frameTime = 1000 / this.fps;
    }

    // 初始化渲染器
    init(physicsEngine) {
        this.physicsEngine = physicsEngine;
        this.mouseX = this.canvas.width / 2;
        this.setupCanvas();
        console.log('渲染器初始化完成');
    }

    // 设置鼠标位置
    setMousePosition(x) {
        this.mouseX = x;
    }

    // 更新渲染器
    update(balls, particles) {
        this.balls = balls || [];
        this.particles = particles || [];
        this.render();
    }

    // 重置渲染器
    reset() {
        this.balls = [];
        this.particles = [];
        this.clearCanvas();
    }

    // 处理窗口大小变化
    handleResize() {
        this.setupCanvas();
    }

    // 截图功能
    takeScreenshot() {
        return this.canvas.toDataURL('image/png');
    }

    // 销毁渲染器
    destroy() {
        this.stopRenderLoop();
    }

    // 获取当前FPS
    getFPS() {
        return this.fps;
    }
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = Renderer;
}